import BleUtils from "../../src/utils/BLEUtil"
import DateUtil from "../../src/utils/DateUtil";
const app=getApp();
//搜索定时器刷新显示设备信息
var interval;
var interval2;
Page({
  data: {
    tab: 0, //0未连接（搜索的设备信息）  1连接成功后
    isLoading: false,
    discovery_txt: "开始搜索蓝牙",
    countdown: 0,
    countdown_txt: "",
    isDiscovery: false,
    sendMsg: "4D011D0000000000000000006B0000",
    receiveMsg:[],
    device: {
      // deviceId: "3B7785F1-F253-B5DF-D00B-0E6BFC70CAD1",
      // name: "D30LE_E6622D"
    },//选中的蓝牙设备
    devices: [
      // {deviceId:'123',name:'ces'},
      // {deviceId:'123',name:'ces'},
      // {deviceId:'123',name:'ces'},
    ],
  },
  test() {
    BleUtils.toast();
  },
  /**
   * 获取发送信息
   * @param {*} e 
   */
  bindTextAreaBlur: function (e) {
    this.setData({
      sendMsg: e.detail.value
    })
  },
  /**
   * 初始化蓝牙适配器 开启扫描
   */
  startSearchBLE() {
    var that = this;
    wx.vibrateShort({
      type: 'heavy',
    })
    if (that.data.isDiscovery) { //再次点击则停止搜索
      that.stopSearchBLE();
    } else {
      //清空之前搜索的devices
      BleUtils.devices = [];
      var promise = BleUtils.initBluetoothAdapte();
      promise.then((res) => {
        if (res == 0) {
          that.setData({
            discovery_txt: "搜索中，再次点击关闭搜索",
            countdown: 15,
            countdown_txt: "15s",
            isLoading: true,
            isDiscovery: true,
            devices: []
          })
          wx.showToast({
            title: '开始搜索蓝牙',
            icon: 'none',
            duration: 2000
          })
          interval2 = setInterval(function () {
            that.setData({
              countdown: that.data.countdown - 1,
              countdown_txt: (that.data.countdown - 1) + "s",
            })
            if (that.data.countdown == 0) {
              clearInterval(interval2);
              that.stopSearchBLE();
            }
          }, 1000);
          interval = setInterval(function () {
            that.setData({
              devices: BleUtils.devices
            })
          }, 500);
        }
      })
    }

  },
  stopSearchBLE() {
    var that = this;
    wx.vibrateShort({
      type: 'heavy',
    });
    wx.showToast({
      title: '停止搜索蓝牙',
      icon: 'none'
    })
    that.setData({
      discovery_txt: "开始搜索蓝牙",
      countdown_txt: "",
      isLoading: false,
      isDiscovery: false,
    })
    var promise = BleUtils.closeBLEConnection();
    promise.then();
    //关闭掉定时器
    clearInterval(interval);
    clearInterval(interval2);
  },
  clickDevice(e) {
    wx.vibrateShort({
      type: 'heavy',
    });
    console.log(e.currentTarget.dataset);
    this.setData({
      device: e.currentTarget.dataset,
    })
    console.log(this.data.isDiscovery);
    if (this.data.isDiscovery) {
      this.stopSearchBLE();
    }
  },
  /**
   * 连接蓝牙
   */
  connectBLE() {
    var that = this;
    wx.vibrateShort({
      type: 'heavy',
    });
    if (that.data.device == null) {
      wx.showToast({
        title: '请选择一个蓝牙设备',
        icon: 'error'
      })
      return;
    }
    if(BleUtils.connected){
      wx.showToast({
        title: '已连接，请先断开连接',
        icon:'none'
      })
      return;
    }
    BleUtils.tryCount = 0;
    BleUtils.deviceId = that.data.device.deviceId;
    BleUtils.ServiceUUID = "0000FFE0-0000-1000-8000-00805F9B34FB";
    BleUtils.ReadUUID = "0000FFE1-0000-1000-8000-00805F9B34FB";
    BleUtils.WriteUUID = "0000FFE1-0000-1000-8000-00805F9B34FB";
    wx.showToast({
      title: '连接中...',
      icon: "loading",
      duration: 300000
    })
    // BleUtils.tryConnect();
    BleUtils.connect(0);
    var tl = setInterval(() => {
      console.log("判断连接状态和连接次数", BleUtils.connected, BleUtils.tryCount)
      if (BleUtils.connected) {
        var device = that.data.device;
        device.status = "已连接";
        that.setData({
          device: device,
          tab: 1,
        })
        clearInterval(tl);
      } else if (!BleUtils.connected && BleUtils.tryCount == 3) {
        var device = that.data.device;
        device.status = "连接失败";
        that.setData({
          device: device,
        })
        wx.hideLoading();
        wx.showToast({
          title: '连接失败',
          icon: 'none'
        })
        clearInterval(tl);
      }
    }, 100);


  },
  /**
   * 断开连接
   */
  closeBLE() {
    wx.vibrateShort({
      type: 'heavy',
    });
    var that = this;
    //判断是否处于已连接状态
    if (BleUtils.connected) {
      var promise = BleUtils.closeBLEConnection(() => {
        wx.showToast({
          title: '断开成功',
          icon: 'none'
        });
        BleUtils.connected = false;
      });
      promise.then();
      var device = that.data.device;
      device.status = "已断开";
      that.setData({
        device: device,
        tab: 0,
      })
    } else {
      wx.showToast({
        title: '未连接蓝牙',
        icon: 'none'
      })
    }
  },
  sendMsg() {
    var that = this;
    console.log(that.data.sendMsg);
    if (that.data.sendMsg == "") {
      wx.showToast({
        title: '请输入需要发送的信息',
        icon: 'none',
      })
      return;
    }
    var msg = that.data.sendMsg.replaceAll(" ", "");
    console.log(msg);
    console.log(msg.length);
    if (msg.length % 2 != 0) {
      wx.showToast({
        title: '输入的数据不符合十六进制',
        icon: 'none',
      })
      return;
    }
    if(BleUtils.connected){
      var promise = BleUtils.sendMsg(msg);
      promise.then((res) => {
        if (res == 0) {
          wx.showToast({
            title: '发送成功',
            icon: 'none',
          })
          wx.onBLECharacteristicValueChange(function (characteristic) {
            that.bleHandler(characteristic);
          })
        }
      })
    }else{
      wx.showToast({
        title: '请先连接蓝牙设备',
        icon:'none'
      })
    }
    
  },
  /**
   * 监听
   */
  bleHandler(characteristic) {
    var that = this;
    console.log("监听数据获取", characteristic);
    var buf = new Uint8Array(characteristic.value)
    console.log("buf长度：", buf.length)
    // console.log(buf);
    var nowrecHEX = app.ab2hex(characteristic.value)
    var receiveMsg=that.data.receiveMsg;
    var date=DateUtil.formatDateTime(new Date(),"yyyy-MM-dd HH:mm:ss");
    receiveMsg.unshift(date+" -> "+nowrecHEX);
    that.setData({
      receiveMsg:receiveMsg
    })
  },
})